<template>
  <div>
       <img :src="userPhotoImg" ref="image"/>
       <van-nav-bar
          class="nav-bar"
          left-text="取消"
          right-text="完成"
          @click-left="$emit('close')"
          @click-right="onConfirm"
         ></van-nav-bar>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs';
import { UserPhoto } from '@/api/user.js'
export default {
  name: 'UpdataPhoto',
  components: { },
  directives: {},
  props:{
     file:{
       //type:[Object,String],
       required:true
     }
  },
  data() {
    return {
         userPhotoImg:window.URL.createObjectURL(this.file),
         cropper:null //裁切器实例
    };
  },
  mounted() {
      //获取需要裁切的图片DOM
      const image=this.$refs.image
      this.cropper = new Cropper(image, {
        viewMode:1,
        dragMode:'move',
        aspectRatio:1,
        cropBoxMovable:false,
        cropBoxResizable:false,
        background:false,
        movable:true
      });
  },
  methods: {
    async onConfirm(){
      this.$toast.loading({
          message:'保存中',
          forbidClick:true,
          duration:0 //展示时间 0表示持续展示
      })
      //裁剪后的图片file
      const file=await this.getCroppedCanvas()
      const fd=new FormData()
      fd.append('photo',file)
      //如果要求 content-Type是multipart/form-data，则一定要提交FormData数据对象，专门用于文件上传
      // const fd=new FormData()
      // fd.append('photo',this.file)
        await  UserPhoto(fd)
        this.$toast.success('保存成功')
        this.$emit('update-photo',window.URL.createObjectURL(file))
        //关闭弹窗
        this.$emit('close');
    },
    getCroppedCanvas(){
      return new Promise((resolve)=>{
        this.cropper.getCroppedCanvas().toBlob((blob)=>{
           resolve(blob)
        })
      })
    }
  },
};
</script>

<style lang="less" scoped>
.nav-bar{
  position:fixed;
  left:0;
  right:0;
  bottom: 0;
  background: #000;
}

img{
   display: block;
   max-width: 100%;
}
</style>
